﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;

namespace Agricultural_Sales.ASP
{
    public partial class Register : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // 清空消息
                lblErrorMessage.Text = "";
                lblSuccessMessage.Text = "";

                // 检查是否已经登录，如果已登录则跳转到首页
                if (Session["UserId"] != null)
                {
                    Response.Redirect("../Default.aspx");
                }
            }
        }

        protected void btnRegister_Click(object sender, EventArgs e)
        {
            try
            {
                string userName = txtUserName.Text.Trim();
                string password = txtPassword.Text.Trim();
                string confirmPassword = txtConfirmPassword.Text.Trim();
                string phone = txtPhone.Text.Trim();
                string address = txtAddress.Text.Trim();

                // 服务器端验证
                if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password) ||
                    string.IsNullOrEmpty(phone) || string.IsNullOrEmpty(address))
                {
                    ShowError("所有字段都不能为空！");
                    return;
                }

                if (password != confirmPassword)
                {
                    ShowError("两次输入的密码不一致！");
                    return;
                }

                if (userName.Length < 3 || userName.Length > 20)
                {
                    ShowError("用户名长度应为3-20个字符！");
                    return;
                }

                if (password.Length < 6 || password.Length > 20)
                {
                    ShowError("密码长度应为6-20个字符！");
                    return;
                }

                // 检查用户名是否已存在
                if (IsUserNameExists(userName))
                {
                    ShowError("用户名已存在，请选择其他用户名！");
                    return;
                }

                // 检查手机号是否已存在
                if (IsPhoneExists(phone))
                {
                    ShowError("该手机号已被注册，请使用其他手机号！");
                    return;
                }

                // 注册用户
                if (RegisterUser(userName, password, phone, address))
                {
                    ShowSuccess("注册成功！正在跳转到登录页面...");
                    // 使用JavaScript实现倒计时跳转
                    ClientScript.RegisterStartupScript(this.GetType(), "successRedirect",
                        "showSuccessWithCountdown();", true);
                }
                else
                {
                    ShowError("注册失败，请稍后重试！");
                }
            }
            catch (Exception ex)
            {
                ShowError("注册过程中发生错误：" + ex.Message);
            }
        }

        // 注册用户到数据库
        // 参数说明：
        // userName - 用户名
        // password - 密码
        // phone - 手机号
        // address - 地址
        // 返回值：注册成功返回true，失败返回false
        private bool RegisterUser(string userName, string password, string phone, string address)
        {
            string connectionString = GetConnectionString();

            try
            {
                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    conn.Open();
                    string sql = @"INSERT INTO Users (UserName, Password, Phone, UserImagee, Address, UserType) 
                                 VALUES (@UserName, @Password, @Phone, @UserImage, @Address, @UserType)";

                    using (SqlCommand cmd = new SqlCommand(sql, conn))
                    {
                        cmd.Parameters.AddWithValue("@UserName", userName);
                        cmd.Parameters.AddWithValue("@Password", password);
                        cmd.Parameters.AddWithValue("@Phone", phone);
                        cmd.Parameters.AddWithValue("@UserImage", "~/Image/user1.jpg"); // 默认头像
                        cmd.Parameters.AddWithValue("@Address", address);
                        cmd.Parameters.AddWithValue("@UserType", "普通用户");

                        int result = cmd.ExecuteNonQuery();
                        return result > 0;
                    }
                }
            }
            catch (Exception ex)
            {
                // 记录错误日志
                System.Diagnostics.Debug.WriteLine("注册用户时发生错误：" + ex.Message);
                throw new Exception("数据库操作失败，请联系系统管理员。");
            }
        }

        // 检查用户名是否已存在
        // 参数说明：
        // userName - 要检查的用户名
        // 返回值：存在返回true，不存在返回false
        private bool IsUserNameExists(string userName)
        {
            string connectionString = GetConnectionString();

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                string sql = "SELECT COUNT(*) FROM Users WHERE UserName = @UserName";

                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    cmd.Parameters.AddWithValue("@UserName", userName);
                    int count = (int)cmd.ExecuteScalar();
                    return count > 0;
                }
            }
        }

        // 检查手机号是否已存在
        // 参数说明：
        // phone - 要检查的手机号
        // 返回值：存在返回true，不存在返回false
        private bool IsPhoneExists(string phone)
        {
            string connectionString = GetConnectionString();

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                string sql = "SELECT COUNT(*) FROM Users WHERE Phone = @Phone";

                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    cmd.Parameters.AddWithValue("@Phone", phone);
                    int count = (int)cmd.ExecuteScalar();
                    return count > 0;
                }
            }
        }

        // 获取数据库连接字符串
        // 返回值：数据库连接字符串
        private string GetConnectionString()
        {
            // 从配置文件中获取连接字符串
            string connectionString = ConfigurationManager.ConnectionStrings["AgriculturalSalesConnectionString"]?.ConnectionString;

            // 如果没有配置连接字符串，使用默认的连接字符串
            if (string.IsNullOrEmpty(connectionString))
            {
                connectionString = @"Data Source=.;Initial Catalog=AgriculturalSales;Integrated Security=True";
            }

            return connectionString;
        }

        // 显示错误消息
        // 参数说明：
        // message - 要显示的错误消息内容
        // 功能：在页面上显示红色的错误提示信息
        private void ShowError(string message)
        {
            lblErrorMessage.Text = message;
            ClientScript.RegisterStartupScript(this.GetType(), "showError",
                "document.getElementById('errorMessage').style.display = 'block'; document.getElementById('successMessage').style.display = 'none'; hideLoading();", true);
        }

        // 显示成功消息
        // 参数说明：
        // message - 要显示的成功消息内容
        // 功能：在页面上显示绿色的成功提示信息，包含倒计时和立即跳转链接
        private void ShowSuccess(string message)
        {
            lblSuccessMessage.Text = message;
            ClientScript.RegisterStartupScript(this.GetType(), "showSuccess",
                @"var successDiv = document.getElementById('successMessage');
          var successLabel = successDiv.querySelector('span') || successDiv.querySelector('label');
          if (successLabel) {
              successLabel.innerHTML = '" + message.Replace("'", "\\'") + @" <a href=""Login.aspx"" style=""color: #2e7d32; text-decoration: underline; margin-left: 10px;"" onclick=""window.location.href=\'Login.aspx\'; return false;"">立即跳转</a>';
          }
          successDiv.style.display = 'block';
          document.getElementById('errorMessage').style.display = 'none';
          hideLoading();
          
          // 3秒后自动跳转
          var countdown = 3;
          var timer = setInterval(function() {
              countdown--;
              if (successLabel) {
                  successLabel.innerHTML = '" + message.Replace("'", "\\'") + @" (<span style=""font-weight:bold"">' + countdown + '</span>秒后自动跳转) <a href=""Login.aspx"" style=""color: #2e7d32; text-decoration: underline; margin-left: 10px;"" onclick=""window.location.href=\'Login.aspx\'; return false;"">立即跳转</a>';
              }
              if (countdown <= 0) {
                  clearInterval(timer);
                  window.location.href = 'Login.aspx';
              }
          }, 1000);", true);
        }
    }
}